package DataSourceOptimize;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 */
public class MyConnection {
    //类加载时初始化
    public static final String URL = "jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8";
    public static final String User ="root";
    public static final String Password ="123456";
    public static DataSource dataSource;
    //类加载时调用
    static {
        MysqlDataSource mysqlDataSource =new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(User);
        mysqlDataSource.setPassword(Password);
        dataSource=mysqlDataSource;
    }
    //获取连接
    public static Connection connection() throws SQLException {
            return dataSource.getConnection();
    }
    //关闭资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
